<?php

namespace app\admin\controller\speech;

use app\common\controller\Backend;
use think\Db;
use think\Debug;
use think\Env;
use think\Request;
use think\Exception;


/**
 *
 *
 * @icon fa fa-circle-o
 */
class Router extends Backend
{

    /**
     * SpeechRouter模型对象
     * @var \app\admin\model\SpeechRouter
     */
    protected $model = null;
    protected $noNeedLogin = ['asyn_json','json_speech1'];

    public function asyn_json($domain,$ids)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $domain.'/admin/speech/router/json_speech1/ids/'.$ids);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT,10);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        $html=curl_exec($ch);
//        var_dump($html);
        curl_close($ch);
    }

    public function json_speech1($ids)
    {
        $path = ROOT_PATH . 'speech_script/' . $ids . '.json';
        $file_dir = '/usr/share/nginx/html/public';
        $arr = array();
        $arr['version'] = '1.1';
        $arr_names = DB::table('fa_speech_router')
            ->field(['name','weigh'])
//            ->distinct(true)
            ->where('speech_id', $ids)
            ->order('weigh')
            ->select();
        $names=array_values(array_unique(array_column($arr_names,"name")));
//        var_dump($names);
        for ($n = 0; $n < count($names); $n++) {
            $routers = DB::table("fa_speech_router")
                ->field(['r.id', 'r.name', 'r.sound_id','r.weigh', 's.name' => 'sound_name', 's.file', 's.tts', 'no_sound_id', 'ns.name' => 'no_name', 'ns.file' => 'no_file', 'ns.tts' => 'no_tts'])
                ->alias('r')
                ->join('fa_sound s', 'r.sound_id=s.id', 'left')
                ->join('fa_sound ns', 'r.no_sound_id=ns.id', 'left')
                ->where('speech_id', $ids)
                ->where('r.name', $names[$n])
                ->order('r.weigh asc')
                ->select();
            $arr["flow"][$n + 1]['name'] = $names[$n];
            $voice = array();
            if (count($routers) > 0) {
                for ($i = 0; $i < count($routers); $i++) {
                    $sound_name = $routers[$i]['sound_name'];
                    $sound_path = $file_dir . $routers[$i]['file'];
                    if ($routers[$i]['tts'] >= 0) {
                        $sound_path = '/tmp/rebot/tts/{$task_id}/{$job_id}-' . $routers[$i]['id'] . '.wav';
                    }
                    if ($routers[$i]['no_sound_id'] == 0) {
                        array_push($voice, array('hint' => $sound_name, 'path' => $sound_path));
                    } else {
                        $no_sound_name = $routers[$i]['no_name'];
                        $no_sound_path = $file_dir . $routers[$i]['no_file'];
                        if ($routers[$i]['no_tts'] >= 0) {
                            $sound_path = '/tmp/rebot/tts/{$task_id}/{$job_id}-' . $routers[$i]['id'] . '-no.wav';
                        }
                        $negative = array("hint" => $no_sound_name, 'path' => $no_sound_path);
                        array_push($voice, array('hint' => $sound_name, 'path' => $sound_path, "negative" => $negative));
                    }
                    $arr["flow"][$n + 1]['voice'] = $voice;
                }
            }
        }

        $arr['positive_words'] = array("好的", "是的", "可以", "行啊", "行的", "没问题", "OK", "好呀", "行呀", "必须的", "对对对", "是啊", "对啊", "需要");
        $arr['negative_words'] = array("不要","不用", "不需要", "不行", "不好", "不感兴趣", "没兴趣", "没需求", "没有", "没想法", "不想要", "不想", "不了解");

        $keywords = DB::table('fa_speech_faq')
            ->field('keyword')
            ->distinct(true)
            ->where('speech_id', $ids)
            ->select();
        $faq_arr = array();
        for ($n = 0; $n < count($keywords); $n++) {
            $voice = array();
            $faqs = DB::table('fa_speech_faq')
                ->field(['f.id', 'keyword', 'sound_id', 's.name', 's.file', 's.tts', 'no_sound_id', 'ns.name' => 'no_name', 'ns.file' => 'no_file', 'ns.tts' => 'no_tts'])
                ->alias('f')
                ->join('fa_sound s', 'f.sound_id=s.id', 'left')
                ->join('fa_sound ns', 'f.no_sound_id=ns.id', 'left')
                ->where('speech_id', $ids)
                ->where('keyword', $keywords[$n]['keyword'])
                ->select();

            if (count($faqs) > 0) {
                for ($j = 0; $j < count($faqs); $j++) {
                    if ($faqs[$j]['keyword'] == '静音') {
                        $arr['silence_prompt_voice'] = array(
                            "hint" => "静音检测",
                            "path" => $file_dir . $faqs[$j]['file']
                        );
                    }
                    if ($faqs[$j]['no_sound_id'] == 0) {
                        array_push($voice,
                            array(
                                'hint' => $faqs[$j]['name'],
                                'path' => $file_dir . $faqs[$j]['file']
                            )
                        );
                    } else {
                        array_push($voice,
                            array(
                                'hint' => $faqs[$j]['name'],
                                'path' => $file_dir . $faqs[$j]['file'],
                                'negative' => array(
                                    "hint" => $faqs[$j]['no_name'],
                                    'path' => $faqs[$j]['no_file']
                                )
                            )
                        );
                    }

                }
                array_push($faq_arr, array(
                    "keywords" => $keywords[$n]['keyword'],
                    'associated_keywords' => $this->get_faq_related($keywords[$n]['keyword']),
                    'misrecognize_keywords' => $this->get_faq_typo($keywords[$n]['keyword']),
                    'voice' => $voice
                ));
            }
        }

        $arr['faq'] = $faq_arr;
        file_put_contents($path, json_encode($arr, JSON_UNESCAPED_UNICODE));
//        print(json_encode($arr, JSON_UNESCAPED_UNICODE));

    }


    public
    function json_speech($ids)
    {
//        $path = Env::get('speech_script_path', '') . '/' . $ids . '.json';
        $path = ROOT_PATH . 'speech_script/' . $ids . '.json';
        $arr = array();
        $arr['version'] = '1.1';
        $routers = Db::name('speech_router')->where('speech_id', $ids)->order('weigh asc')->select();
        $file_dir = '/usr/share/nginx/html/public';
//        var_dump($routers);
        if (count($routers) > 0) {
            for ($i = 0; $i < count($routers); $i++) {
                $arr["flow"][$i + 1]['name'] = $routers[$i]['name'];

                $sound_name = Db::name("sound")->where('id', $routers[$i]['sound_id'])->value('name');
                $sound_url = Db::name("sound")->where('id', $routers[$i]['sound_id'])->value('file');


                //挽回答复
                $no_sound_name = Db::name("sound")->where('id', $routers[$i]['no_sound_id'])->value('name');
                $no_sound_url = Db::name("sound")->where('id', $routers[$i]['no_sound_id'])->value('file');
                $voice = array();

                if (!is_null($no_sound_name) and !is_null($no_sound_url)) {
                    $negative = array("hint" => $no_sound_name, "path" => $file_dir . $no_sound_url);
                    if (isset($routers[$i]['tts'])&&$routers[$i]['tts'] == 1) {
                        array_push($voice, array("hint" => $sound_name, "path" => '/tmp/rebot/tts/{$task_id}/{$job_id}.wav', "negative" => $negative));
                    } else {
                        array_push($voice, array("hint" => $sound_name, "path" => $file_dir . $sound_url, "negative" => $negative));
                    }
                } else {
                    if (isset($routers[$i]['tts']) && $routers[$i]['tts'] == 1) {
                        array_push($voice, array("hint" => $sound_name, "path" => '/tmp/rebot/tts/{$task_id}/{$job_id}.wav'));
                    } else {
                        array_push($voice, array("hint" => $sound_name, "path" => $file_dir . $sound_url));
                    }
                }
                $arr["flow"][$i + 1]['voice'] = $voice;

                //肯定词？？？对应到全局？话术？？
                // $arr['positive_words'] = array('好的', '是的', '对的', '可以');
                $arr['positive_words'] = array("好的", "是的", "可以", "行啊", "行的", "没问题", "OK", "好呀", "行呀", "必须的", "对对对", "是啊", "对啊", "需要");
                //$arr['negative_words'] = array('不要', '不需要', '没兴趣', '不感兴趣', '别烦我', '我很忙', '没时间', '没有');
                $arr['negative_words'] = array("不要", "不需要", "不行", "不好", "不感兴趣", "没兴趣", "没需求", "没有", "没想法", "不想要", "不想", "不了解");
                //FAQ？？？对应到全局？话术
                $faqs = Db::name('speech_faq')->where('speech_id', $ids)->select();
                if (count($faqs) > 0) {
                    $faq_arr = array();
                    for ($j = 0; $j < count($faqs); $j++) {
                        if ($faqs[$j]['no_sound_id'] == null) {
                            array_push($faq_arr,
                                array(
                                    "keywords" => $faqs[$j]['keyword'],
                                    "associated_keywords" => $this->get_faq_related($faqs[$j]['keyword']),
                                    "misrecognize_keywords" => $this->get_faq_typo($faqs[$j]['keyword']),
                                    "voice" => array(array(
                                        "hint" => Db::name("sound")->where('id', $faqs[$j]['sound_id'])->value('name'),
                                        'path' => $file_dir . Db::name("sound")->where('id', $faqs[$j]['sound_id'])->value('file')))));
                        } else {
                            array_push($faq_arr,
                                array(
                                    "keywords" => $faqs[$j]['keyword'],
                                    "associated_keywords" => $this->get_faq_related($faqs[$j]['keyword']),
                                    "misrecognize_keywords" => $this->get_faq_typo($faqs[$j]['keyword']),
                                    "voice" => array(array(
                                        "hint" => Db::name("sound")->where('id', $faqs[$j]['sound_id'])->value('name'),
                                        'path' => $file_dir . Db::name("sound")->where('id', $faqs[$j]['sound_id'])->value('file'),
                                        'negative' => array(
                                            "hint" => Db::name("sound")->where('id', $faqs[$j]['no_sound_id'])->value('name'),
                                            'path' => $file_dir . Db::name("sound")->where('id', $faqs[$j]['no_sound_id'])->value('file')
                                        ))
                                    )));
                        }
                    }
                    $arr['faq'] = $faq_arr;
                    if (Db::name('speech_faq')->where('speech_id', $ids)->where('keyword', '静音')->count() > 0) {
                        $faq = Db::name('speech_faq')->where('speech_id', $ids)->where('keyword', '静音')->find();
                        $arr['silence_prompt_voice'] = array(
                            "hint" => "您好，您还在吗",
                            "path" => $file_dir . Db::name('sound')->where('id', $faq['sound_id'])->value('file')
                        );
                    }
                }
            }
        }
        file_put_contents($path, json_encode($arr, JSON_UNESCAPED_UNICODE));
    }

    private
    function get_faq_related($keyword)
    {
        $keyword = str_replace("，", ",", $keyword);
        $keyword = str_replace("、", ",", $keyword);
        $keyword = str_replace("\r\n", ",", $keyword);
        $related = "";
        foreach (explode(",", $keyword) as $key) {
            if (!is_null(Db::name('faq_related')->where('keyword', $key)->value('related'))) {
                $related .= Db::name('faq_related')->where('keyword', $key)->value('related');
                $related .= ",";
            }
        }
        $arr = explode(",", $related);
        $related = implode(",", array_unique($arr));
        return $related;
    }

    private
    function get_faq_typo($keyword)
    {
        $keyword = str_replace("，", ",", $keyword);
        $keyword = str_replace("、", ",", $keyword);
        $keyword = str_replace("\r\n", ",", $keyword);
        $typo = "";
        foreach (explode(",", $keyword) as $key) {
            if (!is_null(Db::name('faq_typo')->where('keyword', $key)->value('typo'))) {
                $typo .= Db::name('faq_typo')->where('keyword', $key)->value('typo');
                $typo .= ",";
            }
        }
        $arr = explode(",", $typo);
        $typo = implode(",", array_unique($arr));
        return $typo;
    }

    public
    function _initialize()
    {
        parent::_initialize();
        $this->model = model('SpeechRouter');
        $this->view->assign("statusList", $this->model->getStatusList());
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 添加
     */
    public function add()
    {

        $speech_id = $this->request->only("speech_id");
//        var_dump($speech_id);
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                try {

                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = basename(str_replace('\\', '/', get_class($this->model)));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : true) : $this->modelValidate;
                        $this->model->validate($validate);
                    }
                    $check = Db::name('speech_router')
                        ->where('speech_id',$params['speech_id'])
                        ->where('name',$params['name'])
                        ->count();
                    if($check >=3)
                    {
                        $this->error('最多只能添加三条');
                    }


                    $count1 = Db::name('sound')
                        ->where('id',$params['sound_id'])
                        ->where('tts','<>',-1)
                        ->count();
                    $count2 = Db::name('sound')
                        ->where('id',$params['no_sound_id'])
                        ->where('tts','<>',-1)
                        ->count();
                    $soundInfo = $count1 + $count2;
                    $soundCheck = Db::name('speech_router')
                        ->alias('r')
                        ->join('sound s','s.id = r.sound_id or s.id = r.no_sound_id')
                        ->where('s.tts','<>',-1)
                        ->where('r.speech_id',$params['speech_id'])
                        ->count();
                    Db::startTrans();
                    if($soundInfo==0)
                    {
                        $result = $this->model->allowField(true)->save($params);

                    }else{

                        if($soundInfo + $soundCheck>1)
                        {
                            $this->error('只能添加一条tts语音');
                        }

                        $result = $this->model->allowField(true)->save($params);
                        $soundCheck +=1;
                    }

                    $check +=1;
                    $weigh = Db::name('speech_router')
                        ->where('id',$this->model->id)
                        ->value('weigh');


                    if( !$this->request->post('sound_id2')&&$this->request->post('no_sound_id2'))
                    {
                        Db::rollback();
                        $this->error('请选择引导语音');
                    }

                    if($this->request->post('sound_id2'))
                    {
                        if($this->request->post('sound_id2') == $params['sound_id'])
                        {
                            Db::rollback();
                            $this->error('选择的语音重复，请重新添加');
                        }

                        if($check >3)
                        {
                            Db::rollback();
                            $this->error('最多只能添加三条');
                        }

                        $count1 = Db::name('sound')
                            ->where('id',$this->request->post('sound_id2'))
                            ->where('tts','<>',-1)
                            ->count();
                        $count2 = Db::name('sound')
                            ->where('id',$this->request->post('no_sound_id2'))
                            ->where('tts','<>',-1)
                            ->count();
                        $soundInfo2 = $count1 + $count2;
                        if($soundInfo2 ==0)
                        {
                            Db::name('speech_router')
                                ->insert([
                                    'name' => $params['name'],
                                    'speech_id' => $params['speech_id'],
                                    'weigh'     => $weigh,
                                    'sound_id'  => $this->request->post('sound_id2'),
                                    'no_sound_id'=>$this->request->post('no_sound_id2')?:0,
                                    'admin_id'  => $this->auth->id,
                                ]);
                            $check +=1;
                        }else{
                            if($soundInfo2 + $soundCheck>1)
                            {
                                Db::rollback();
                                $this->error('只能添加一条tts语音');
                            }

                            Db::name('speech_router')
                                ->insert([
                                    'name' => $params['name'],
                                    'speech_id' => $params['speech_id'],
                                    'weigh'     => $weigh,
                                    'sound_id'  => $this->request->post('sound_id2'),
                                    'no_sound_id'=>$this->request->post('no_sound_id2')?:0,
                                    'admin_id'  => $this->auth->id,
                                ]);
                            $check +=1;
                            $soundCheck +=1;
                        }


                        $check +=1;
                    }

                    if( !$this->request->post('sound_id3')&&$this->request->post('no_sound_id3'))
                    {
                        Db::rollback();
                        $this->error('请选择引导语音');
                    }
                    if($this->request->post('sound_id3'))
                    {
                        if(($this->request->post('sound_id3') == $params['sound_id']) || ($this->request->post('sound_id3')==$this->request->post('sound_id2')))
                        {
                            Db::rollback();
                            $this->error('选择的语音重复，请重新添加');
                        }
                        if($check >3)
                        {
                            Db::rollback();
                            $this->error('最多只能添加三条');
                        }

                        $count1 = Db::name('sound')
                            ->where('id',$this->request->post('sound_id3'))
                            ->where('tts','<>',-1)
                            ->count();
                        $count2 = Db::name('sound')
                            ->where('id',$this->request->post('no_sound_id3'))
                            ->where('tts','<>',-1)
                            ->count();
                        $soundInfo3 = $count1 + $count2;

                        if($soundInfo3 ==0)
                        {
                            Db::name('speech_router')
                                ->insert([
                                    'name' => $params['name'],
                                    'weigh'     => $weigh,
                                    'speech_id' => $params['speech_id'],
                                    'sound_id'  => $this->request->post('sound_id3'),
                                    'no_sound_id'=>$this->request->post('no_sound_id3')?:0,
                                    'admin_id'  => $this->auth->id,
                                ]);
                        }else{

                            if($soundInfo3 + $soundCheck>1)
                            {
                                Db::rollback();
                                $this->error('只能添加一条tts语音');
                            }

                            Db::name('speech_router')
                                ->insert([
                                    'name' => $params['name'],
                                    'weigh'     => $weigh,
                                    'speech_id' => $params['speech_id'],
                                    'sound_id'  => $this->request->post('sound_id3'),
                                    'no_sound_id'=>$this->request->post('no_sound_id3')?:0,
                                    'admin_id'  => $this->auth->id,
                                ]);

                        }


                    }

                    if ($result !== false) {
                        Db::commit();
                        $this->success();
                    } else {
                        $this->error($this->model->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    public function line_edit()
    {
        $oldName = $this->request->post('old_name');
        $name = $this->request->post('name');
        $speechId = $this->request->post('speech_id');

        if(!$name || !$oldName || !$speechId)
        {
            $this->error('参数错误');
        }

        Db::name('speech_router')
            ->where('name',$oldName)
            ->where('admin_id',$this->auth->id)
            ->where('speech_id',$speechId)
            ->update(['name'=>$name]);
        $this->success();
    }

    public function edit($ids = NULL)
    {

        $row = $this->model->get($ids);
        $speechId = Db::name('speech_router')
            ->where('id',$ids)
            ->value('speech_id');
        if (!$row)
            $this->error(__('No Results were found'));
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }

        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                try {

                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = basename(str_replace('\\', '/', get_class($this->model)));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : true) : $this->modelValidate;
                        $this->model->validate($validate);
                    }

                    $result = $row->allowField(true)->save($params);


                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($this->model->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        $this->view->assign('router_id', $ids);
        $this->view->assign('speech_id', $speechId);
        return $this->view->fetch();
    }


    /**
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 话术页面的下拉展开
     */
    public function detail()
    {
        $speechId = $this->request->get('speech_id');
        $routerId = $this->request->get('router_id');
        if (!$routerId) {
            $this->error('参数错误');
        }
        $routerInfo = Db::name('speech_router')
            ->where('id', $routerId)
            ->find();

        if (!$routerInfo) {
            $this->error('系统错误');
        }
        $data = Db::name('sound')
            ->alias('s')
            ->join('speech_router r','s.id = r.sound_id','left')
            ->where('r.name',$routerInfo['name'])
//            ->where('r.admin_id',$this->auth->id)
            ->where('r.speech_id',$speechId)
            ->field('r.id,r.name,r.sound_id,s.name as file_name,s.file,s.content,s.tts')
            ->select();

        $data1 = Db::name('sound')
            ->alias('s')
            ->join('speech_router r','s.id =r.no_sound_id','left')
            ->where('r.name',$routerInfo['name'])
//            ->where('r.admin_id',$this->auth->id)
            ->where('r.speech_id',$speechId)
            ->field('r.id,r.name as no_name,r.no_sound_id as sound_id,s.name as file_name,s.file,s.content,s.tts')
            ->select();

        $router = array_merge($data,$data1);

        $arr = [];
        foreach ($router as $value)
        {
            $arr[$value['id']]['id'] = $value['id'];

            if(isset($value['name']))
            {
                $arr[$value['id']]['name'] = $value['name'];
                $arr[$value['id']]['file'] = $value['file'];
                $arr[$value['id']]['sound_id'] = $value['sound_id'];
                $arr[$value['id']]['file_name'] = $value['file_name'];
                $arr[$value['id']]['content'] = $value['content'];
                $arr[$value['id']]['tts'] = $value['tts'];

            }
            if(isset($value['no_name']))
            {
                $arr[$value['id']]['no_name'] = $value['no_name'];
                $arr[$value['id']]['no_file'] = $value['file'];
                $arr[$value['id']]['no_sound_id'] = $value['sound_id'];
                $arr[$value['id']]['no_file_name'] = $value['file_name'];
                $arr[$value['id']]['no_content'] = $value['content'];
                $arr[$value['id']]['no_tts'] = $value['tts'];
            }
        }
        $arr = array_values($arr);

        return json($arr);
    }

    /**
     * 查看
     */
    public function index()
    {


        $speechId = $this->request->get('speech_id');

//        $this->json_speech1($this->request->get('speech_id'));
        $this->asyn_json(Request::instance()->domain(),$this->request->get('speech_id'));


        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags']);


        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();


            $total = $this->model
                ->with(['sound', 'speech'])
                ->where($where)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->with(['sound', 'speech'])
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            foreach ($list as $row) {
                $row->getRelation('sound')->visible(['id', 'name', 'file', 'file_size','tts']);
                $row->getRelation('speech')->visible(['id', 'name', 'admin_id']);
            }
            $list = collection($list)->toArray();

            $nunList = count($list);
            for ($i = 0; $i < $nunList; $i++) {
                $no_sound_id = $list[$i]['no_sound_id'];
                if ($no_sound_id == 0) {
                    $no_sound_id = $list[$i]['sound_id'];
                }
                $list[$i]['no_sound'] = array(
                    'id' => $no_sound_id,
                    'name' => Db::name('sound')->where('id', $no_sound_id)->value('name'),
                    'file' => Db::name('sound')->where('id', $no_sound_id)->value('file'),
                    'file_size' => Db::name('sound')->where('id', $no_sound_id)->value('file')
                );

            }

            $speechId = isset($list[0]['speech_id'])?$list[0]['speech_id']:'';

            foreach ($list as &$value)
            {

                $num = Db::name('speech_router')
                    ->where('name',$value['name'])
                    ->where('sound_id','<>','')
//                    ->where('admin_id',$this->auth->id)
                    ->where('speech_id',$speechId)
                    ->count();

                $noNum = Db::name('speech_router')
                    ->where('name',$value['name'])
                    ->where('no_sound_id','<>','')
//                    ->where('admin_id',$this->auth->id)
                    ->where('speech_id',$speechId)
                    ->count();

                $value['num'] = $num;
                $value['no_num'] = $noNum;
            }

            $out = [];
            $arr = [];
            
            foreach ($list as $key=>&$value) {

                if (!in_array($value['name'], $out))
                {
                    $out[$key] = $value['name'];
                    $arr[] = $value;
                }
            }

            $result = array("total" => $total, "rows" => $arr);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 行内添加
     */
    public function append()
    {
        $speechId = $this->request->post('speech_id');
        $name = $this->request->post('name');
        $soundId = $this->request->post('sound_id');
        $noSoundId = $this->request->post('no_sound_id');
        if(!$name || !$soundId || !$noSoundId)
        {
            $this->error('参数错误');
        }
        $result = Db::name('speech_router')
            ->where('name',$name)
            ->where('speech_id',$speechId)
            ->find();
        if(!$result)
        {
            $this->error('系统错误');
        }
        try{
            $data = [
                'name'        => $name,
                'sound_id'    => $soundId,
                'no_sound_id' => $noSoundId,
                'speech_id'   => $speechId,
                'weigh'       => $result['weigh'],
                'status'      => '1',
                'admin_id'    => $this->auth->id,
            ];
            Db::name('speech_router')
                ->insert($data);
            $this->success();
        }catch (Exception $e){
            $this->error($e->getMessage());
        }


    }


    /**
     * 编辑改写
     */
    public function modify()
    {
        $array      =json_decode($_POST['array']);

        $name       = $this->request->post('name');
        $speechId   = $this->request->post('speech_id');

        if(!$array)
        {
            $this->error('参数错误');
        }

        $arr = [];
        foreach ($array as $value)
        {
            $arr[] = (array)$value;
        }

        foreach ($arr as $val)
        {
            if(!isset($val['sound_id']))
            {
                $this->error('请选择引导语音');
            }
        }


        $weigh = '';
        foreach ($arr as $key =>$value){

            if (in_array($value['sound_id'], $arr))
            {
                $this->error('选择的语音重复，请重新选择');
            }else{
                $arr[$key] = $value['sound_id'];
            }

            $noSoundId = isset($value['no_sound_id'])?$value['no_sound_id']:'';
            $s1 = Db::name('sound')
                ->where('id',$value['sound_id'])
                ->field('tts')
                ->find();
            $s2 = Db::name('sound')
                ->where('id',$noSoundId)
                ->field('tts')
                ->find();
            $num = 0;
            if($s1 && $s1['tts']!=-1)
            {
                $num+=1;
            }
            if($s2 && $s2['tts']!=-1)
            {
                $num+=1;
            }

            $soundInfo = Db::name('speech_router')
                ->alias('r')
                ->join('sound s','s.id = r.sound_id or s.id = r.no_sound_id')
                ->where('s.tts','<>',-1)
                ->where('r.speech_id',$speechId)
                ->field('r.id,r.name,r.sound_id,s.tts')
                ->select();
            $soundCheck = count($soundInfo);

            if(isset($value['id']))
            {

                if(isset($soundInfo[0]['id']) && $soundInfo[0]['id'] == $value['id'])
                {
                    $soundCheck = 0;
                }
                $weigh = Db::name('speech_router')
                    ->where('id',$value['id'])
                    ->value('weigh');
                if($num == 0){
                    Db::name('speech_router')
                        ->where('id',$value['id'])
                        ->update([
                            'sound_id'      => $value['sound_id'],
                            'no_sound_id'   => $noSoundId
                        ]);
                }else{
                    if($num+$soundCheck>1)
                    {
                        $this->error('只能添加一条tts语音');
                    }

                    Db::name('speech_router')
                        ->where('id',$value['id'])
                        ->update([
                            'sound_id'      => $value['sound_id'],
                            'no_sound_id'   => $noSoundId
                        ]);
                }

            }else{
                if($num == 0)
                {
                    Db::name('speech_router')
                        ->insert([
                            'name' => $name,
                            'weigh' => $weigh,
                            'speech_id' => $speechId,
                            'sound_id'  => $value['sound_id'],
                            'no_sound_id'=>isset($value['no_sound_id'])?$value['no_sound_id']:'',
                            'admin_id'  => $this->auth->id,
                        ]);
                }else{
                    if($num+$soundCheck>1)
                    {
                        $this->error('只能添加一条tts语音');
                    }

                    Db::name('speech_router')
                        ->insert([
                            'name' => $name,
                            'weigh' => $weigh,
                            'speech_id' => $speechId,
                            'sound_id'  => $value['sound_id'],
                            'no_sound_id'=>isset($value['no_sound_id'])?$value['no_sound_id']:'',
                            'admin_id'  => $this->auth->id,
                        ]);
                }

            }
        }


        $this->success();
    }

    /**
     * 全面删除
     */
    public function drop()
    {
        $speechId = $this->request->post('speech_id');
        $name     = $this->request->post('name');

        if(!$speechId || !$name)
        {
            $this->error('参数错误');
        }
        $data = Db::name('speech_router')
            ->where('speech_id',$speechId)
            ->where('name',$name)
//            ->where('admin_id',$this->auth->id)
            ->delete();

        $this->success();
    }

    public function routers()
    {
        $speechId = $this->request->get('speech_id');
        if(!$speechId)
        {
            $this->error('参数错误');
        }
        $keyword = $this->request->get('keyword');
        if($keyword)
        {
            $where = ['name' => ['like','%'.$keyword.'%']];
        }

        $data = Db::name('speech_router')
            ->where('admin_id',$this->auth->id)
            ->where($where)
            ->select();
        $count = Db::name('speech_router')
            ->where('admin_id',$this->auth->id)
            ->where($where)
            ->count();
        $response = [
            'data'  =>$data,
            'total' => $count,
        ];

        return json($response);

    }

}
